#!/bin/bash

VERSION=2009.08.29
PROGNAME="${0##*/}"

die() {
	echo $*
	exit 1
}

mknod() {
	echo "Creating device node $1"
	/bin/mknod $* || return 1
}

blurb() {
cat << EOF
Funtoo $PROGNAME version $VERSION

EOF
}

help() {
	echo "HELP"
}

blurb

if [ $# -eq 0 ] || [ "$1" = "--help" ]
then
cat << EOF
Copyright 2009 Funtoo Technologies; All rights reserved.
Distributed under the 2-clause BSD License.

Usage: $PROGNAME DIRECTORY

This script will create base device nodes and symlinks in directory DIRECTORY.
These device nodes and symlinks will be sufficient for initial system boot
prior to udev starting, chroot-based environments, and container environments
such as OpenVZ, in a situation where the user chooses not to use udev.

This script is also used by the udev ebuild to populate /lib/udev/devices,
which contains the initial set of device nodes that are copied to /dev by
udev when it starts.

This script will not replace existing device nodes with new device nodes.
However, if a non-device exists where a device should exist, the non-device
will first be removed and the device node will be created in its place with
standard permissions. This is useful in situations where invalid /dev/null or
similar files may be exist - they will be replaced with proper device nodes.

Symbolic links are created with the -f option, so any destination files
or devices that exist in the directory will be removed first if they exist.

EOF
	exit 0
fi

cd $1 || die "Could not change directory to $1."

! [ -c console ] && rm -rf console
[ -e console ] || { mknod console c 5 1 && chmod 600 console; } || die

! [ -c null ] && rm -rf null
[ -e null ] || { mknod null c 1 3 && chmod 777 null; } || die

! [ -c tty ] && rm -rf tty
[ -e tty ] || { mknod tty c 5 0 && chmod 666 tty; } || die

! [ -c ttyp0 ] && rm -rf ttyp0
[ -e ttyp0 ] || { mknod ttyp0 c 3 0 && chmod 644 ttyp0; } || die

! [ -c ptyp0 ] && rm -rf ptyp0
[ -e ptyp0 ] || { mknod ptyp0 c 2 0 && chmod 644 ptyp0; } || die

! [ -c ptmx ] && rm -rf ptmx
[ -e ptmx ] || { mknod ptmx c 5 2 && chmod 666 ptmx; } || die

! [ -c tty0 ] && rm -rf tty0
[ -e tty0 ] || { mknod tty0 c 4 0 && chmod 666 tty0; } || die

! [ -c urandom ] && rm -rf urandom
[ -e urandom ] || { mknod urandom c 1 9 && chmod 666 urandom; } || die

! [ -c random ] && rm -rf random
[ -e random ] || { mknod random c 1 8 && chmod 666 random; } || die

! [ -c zero ] && rm -rf zero
[ -e zero ] || { mknod zero c 1 5 && chmod 666 zero; } || die

! [ -c kmsg ] && rm -rf kmsg
[ -e kmsg ] || { mknod kmsg c 1 11 && chmod 600 kmsg; } || die

for x in 0 1 2 3
do
	# These devices are for initial serial console
	! [ -c ttyS${x} ] && rm -rf ttyS${x}
	[ -e ttyS${x} ] || { mknod ttyS${x} c 4 $(( 64 + $x )) && chmod 600 ttyS${x}; } || die
done

[ -d fd ] || ln -svf /proc/self/fd fd || die
ln -svf /proc/self/fd/0 stdin || die
ln -svf /proc/self/fd/1 stdout || die
ln -svf /proc/self/fd/2 stderr || die
ln -svf /proc/kcore core || die
